﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using xxpl1.Cache;
using xxpl1.HTTP.Parser;
using xxpl1.HTTP.Runtime;
using xxpl1.Utils;

namespace xxpl1.GAE.Simple2
{
    public class SaveCacheHandler : IHttpRequestHandler
    {
        public void Execute(HandlerContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            if (Settings.Instance.EnableCache
                && context.Result == HanlderReult.Ok
                && "GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase)
                && response.CanCache
                && !response.IsFromCache
                )
            {
                ThreadPool.QueueUserWorkItem(CacheResponse, context);
            }
        }

        private static void CacheResponse(object state)
        {
            HandlerContext context = state as HandlerContext;
            HttpResponse response = context.Response;
            HttpRequest request = context.Request;

            MemoryStream ms = new MemoryStream();

            response.RenderToCacheStream(ms);

            ms.Flush();

            DiskCacheFactory.GetDiskCache().Set(request.RawUrl, ms.ToArray(), response.Exipre);
        }
    }
}
